﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using LinkCard.Model;

namespace LinkCard.Dao
{
    public class DealDao : ITopLinkDao
    {
        public int Add(object obj)
        {
            var rs = 0;
            try
            {
                var db = new TopLinkEntities();
                var objAdd = (Deal)obj;
                db.AddToDeal(objAdd);
                rs = db.SaveChanges();
            }
            catch (Exception ex)
            {
                throw ex;
            }
            return rs;
        }

        public int Update(object obj)
        {
            var rs = 0;
            try
            {
                var db = new TopLinkEntities();
                var objUpdate = (Deal)obj;
                var id = objUpdate.DealID;
                var oldObj = db.Deal.FirstOrDefault(t => t.DealID == id);
                if (oldObj != null)
                {
                    oldObj.CategoryID = objUpdate.CategoryID;
                    oldObj.SupplierID = objUpdate.SupplierID;
                    oldObj.Name = objUpdate.Name;
                    oldObj.Description = objUpdate.Description;
                    oldObj.Detail = objUpdate.Detail;
                    oldObj.Price = objUpdate.Price;
                    oldObj.Discounting = objUpdate.Discounting;
                    oldObj.TopLinkRate = objUpdate.TopLinkRate;
                    oldObj.Point = objUpdate.Point;
                    oldObj.EndDate = objUpdate.EndDate;
                    oldObj.PostDate = objUpdate.PostDate;
                    oldObj.Status = objUpdate.Status;
                    oldObj.AlbumID = objUpdate.AlbumID;
                    oldObj.Version = objUpdate.Version;
                    oldObj.Image = objUpdate.Image;
                    rs = db.SaveChanges();
                }
            }
            catch (Exception ex)
            {
                throw ex;
            }
            return rs;
        }

        public int Delete(object obj)
        {
            var rs = 0;
            try
            {
                var db = new TopLinkEntities();
                var objDel = (Deal)obj;
                var id = objDel.DealID;
                var oldObj = db.Deal.FirstOrDefault(t => t.DealID == id);
                if (oldObj != null)
                {
                    db.DeleteObject(oldObj);
                    rs = db.SaveChanges();
                }
            }
            catch (Exception ex)
            {
                throw ex;
            }
            return rs;
        }

        public Deal GetById(long id)
        {
            var ct = new Deal();
            try
            {
                var db = new TopLinkEntities();
                ct = db.Deal.FirstOrDefault(t => t.DealID == id);
            }
            catch (Exception)
            {
                throw;
            }
            return ct;
        }

        public List<Deal> GetAll()
        {
            var lst = new List<Deal>();
            try
            {
                var db = new TopLinkEntities();
                lst = db.Deal.ToList();
            }
            catch (Exception)
            {
                throw;
            }
            return lst;
        }

        public List<Deal> GetAllBySupplier(Int64 iSupplierID)
        {
            var lst = new List<Deal>();
            try
            {
                var db = new TopLinkEntities();
                lst = db.Deal.Where(t => t.SupplierID == iSupplierID && t.Status == 2).ToList();
            }
            catch (Exception)
            {
                throw;
            }
            return lst;
        }

        /// <summary>
        /// Ordered by OrderByDescending PostDate
        /// </summary>
        /// <param name="supplierID"></param>
        /// <param name="currentPage"></param>
        /// <param name="pageSize"></param>
        /// <param name="pageCount"></param>
        /// <returns></returns>
        public List<Deal> GetAllBySupplierPaged(Int64 supplierID, int currentPage, int pageSize, ref int pageCount)
        {
            var lst = new List<Deal>();
            try
            {
                var db = new TopLinkEntities();
                // Count pages
                int dealCount = db.Deal.Where(d => d.SupplierID == supplierID && d.Status == 2).Count();
                //int skip = currentPage * pageSize;
                int skip = (currentPage - 1) * pageSize;
                lst = db.Deal.Where(d => d.SupplierID == supplierID && d.Status == 2).OrderByDescending(d => d.PostDate).ThenByDescending(d => d.DealID).Skip(skip).Take(pageSize).ToList();


                if (dealCount % pageSize == 0)
                    pageCount = dealCount / pageSize;
                else
                    pageCount = Convert.ToInt32(dealCount / pageSize) + 1;
            }
            catch (Exception ex)
            {
                throw ex;
            }

            return lst;
        }

        public List<Deal> GetLatestDeal(int count)
        {
            try
            {
                using (TopLinkEntities db = new TopLinkEntities())
                {
                    return db.Deal.Where(q => q.Status == 2).OrderByDescending(q => q.PostDate).Take(count).ToList();
                }
            }
            catch
            {
                return new List<Deal>();
            }
        }

        public List<Deal> GetLatestDealBySupplier(long supplierid, int count)
        {
            try
            {
                using (TopLinkEntities db = new TopLinkEntities())
                {
                    return db.Deal.Where(q => q.Status == 2 && q.SupplierID == supplierid).OrderByDescending(q => q.PostDate).Take(count).ToList();
                }
            }
            catch
            {
                return new List<Deal>();
            }
        }

        public List<ShortDeal> GetLatestDealByCategory(long categoryid, int count)
        {
            try
            {
                string cmttext = "select top " + count + " A.DealId,A.CategoryID,A.Description, A.SupplierID, A.Name, A.Price,A.Discounting, A.TopLinkRate,A.Point,A.EndDate,A.Image from  Deal as A where A.Status=2 and (A.CategoryId =" + categoryid + " or A.CategoryId in (select CategoryID from dbo.Category where ParentId=" + categoryid + "))";
                using (TopLinkEntities db = new TopLinkEntities())
                {
                    return db.ExecuteStoreQuery<ShortDeal>(cmttext, null).ToList();
                }
            }
            catch
            {
                return new List<ShortDeal>();
            }
        }

        public List<ShortDeal> GetLatestDealByCategory(long categoryid, int page, int pagesize, int startindex = 5)
        {
            try
            {
                string cmttext = "select A.DealId,A.CategoryID, A.SupplierID, A.Name,A.Description, A.Price,A.Discounting, A.TopLinkRate,A.Point,A.EndDate,A.Image from (SELECT ROW_NUMBER() OVER (ORDER BY D.PostDate DESC) AS Row,D.* from Deal as D where D.Status=2 and (D.CategoryId =" + categoryid + " or D.CategoryId in (select CategoryID from dbo.Category where ParentId=" + categoryid + ")))as A where A.Row >= " + ((page - 1) * pagesize) + startindex + " AND A.Row <" + (page * pagesize + startindex);
                using (TopLinkEntities db = new TopLinkEntities())
                {
                    return db.ExecuteStoreQuery<ShortDeal>(cmttext, null).ToList();
                }
            }
            catch
            {
                return new List<ShortDeal>();
            }
        }

        public List<ShortDeal> GetDealByTag(string tag,int page,int pagesize)
        {
            List<ShortDeal> source;
            try
            {
                using (TopLinkEntities db = new TopLinkEntities())
                {
                    var deals = db.Deal.Where(q => q.Status == 2 && ("," + q.Tags.Trim().ToLower() + ",").Replace(", ", ",").Replace(" ,", ",").Contains("," + tag.Trim().ToLower() + ",")).OrderByDescending(q => q.PostDate).Skip((page - 1) * pagesize).Take(pagesize).ToList();
                    source = GetShortDeal(deals);
                }
            }
            catch
            {
                return new List<ShortDeal>();
            }
            return source;
        }

        public int GetTotalRecord(long categoryid)
        {
            string cmdText = "select count(*) from Deal D where D.Status=2 and (D.CategoryId =" + categoryid + " or D.CategoryId in (select CategoryID from dbo.Category where ParentId=" + categoryid + "))";
            using (TopLinkEntities db = new TopLinkEntities())
            {
                return db.ExecuteStoreQuery<int>(cmdText, null).ToList()[0];
            }
        }

        public List<Deal> GetSameDeal(long currentdeal, long categoryid, int count = 4)
        {
            try
            {
                using (TopLinkEntities db = new TopLinkEntities())
                {
                    return db.Deal.Where(q => q.CategoryID == categoryid && q.Status == 2 && q.DealID != currentdeal).OrderByDescending(q => q.PostDate).Take(count).ToList();
                }
            }
            catch (Exception)
            {
                return new List<Deal>();
            }


        }

        public static List<ShortDeal> GetShortDeal(List<Deal> deals)
        {
            return (from item in deals
                    select new ShortDeal()
                    {
                        DealID = item.DealID,
                        CategoryID = item.CategoryID,
                        Description = item.Description,
                        Discounting = item.Discounting,
                        EndDate = item.EndDate,
                        Image = item.Image,
                        Name = item.Name,
                        Point = item.Point,
                        Price = item.Price,
                        SupplierID = item.SupplierID,
                        TopLinkRate = item.TopLinkRate
                    }).ToList();
        }
    }
}
